package com.study.thread;

import com.study.utils.SysUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author study
 * @version 1.0
 * @date 2020/6/16 1:30
 */
public class Demo extends Thread {
    private static Logger logger = LoggerFactory.getLogger(Demo.class);
    /**
     * 控制状态
     */
    private volatile boolean desstatus = true;

    /**
     * 重写线程销毁方法，安全的关闭线程|一般run方法执行完就执行完了现场
     */
    @Override
    public void destroy() {
        setDesStatus(false);
    }

    public void setDesStatus(boolean desStatus) {
        this.desstatus = desStatus;
    }

    @Override
    public void run() {

        int i = 0;
        try {
            while (desstatus && i < 10) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(String.format("%-5s|%-20s%-5s", this.isAlive(), SysUtils.getDateSpan(), i));
                i++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (this.isAlive()) {
                destroy();
                logger.info("关闭线程");
                System.out.println(this.isAlive());
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Demo demo = new Demo();
        demo.start();
        TimeUnit.SECONDS.sleep(3);
        demo.destroy();
        while (demo.isAlive()) {
            //右对齐 自动补全 空格
            System.out.println(String.format("%-20s", "demo alive"));
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(String.format("%20s", "demo dead"));
    }
}
